package org.redmagic.service.controller;

import java.net.URI;

import javax.servlet.http.HttpServletRequest;

import org.redmagic.service.dao.PlaceholderDao;
import org.redmagic.service.domain.Property;
import org.redmagic.service.utils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.UriComponents;

@Controller
public class PostPropertyController {

    private static final String PROPERTY_VALUE_HEADER = "BlueMagicPropertyValue";
    
    @Autowired
    private PlaceholderDao dao;
    
    @RequestMapping(value="/property/**", method=RequestMethod.POST, headers=PROPERTY_VALUE_HEADER)
    public ResponseEntity<String> createProperty(HttpServletRequest request, @RequestHeader(PROPERTY_VALUE_HEADER) String value) {
        Property property = PropertyUtils.create(request, "/property/");
        property.setValue(value);
        System.out.println("[POST] Creating property..." + property);
        dao.post(property);
        String propertyPath = PropertyUtils.toUrlForm(property);
        UriComponents uriComponents = ServletUriComponentsBuilder.fromServletMapping(request).path("/property/" + propertyPath).build();
        URI location = uriComponents.toUri();
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(location);
        return new ResponseEntity<String>(headers, HttpStatus.CREATED);
    }
}